package com.sh169.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.ioc.Ioc;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;

import com.sh169.beans.ApplicationConfig;
import com.sh169.beans.UserHolder;
import com.sh169.pojos.User;
import com.sh169.service.AuthHomeService;
import com.sh169.util.BaseHttpFilter;
import com.sh169.util.Md5;
/**
 * 处理 登录验证操作：
 *      有当前用户时，返回到首页
 *      若用户用户名和密码不正确或状态不对
 *          返回到登录页面，并提示错误信息
 *      登录成功后，返回到以前页面，若没有则返回到首页。
 * @author Administrator
 *
 */
public class CheckLoginFilter extends BaseHttpFilter{
	private static Log log = Logs.getLog(CheckLoginFilter.class);
	private AuthHomeService authHomeService;

	private boolean requireCheckLogin(HttpServletRequest request){
		log.debug("request uri: "+request.getRequestURI());
		log.info("check login filter: "+request.getContextPath()+ApplicationConfig.getCheck_uri());
		if(request.getRequestURI().endsWith(request.getContextPath()+ApplicationConfig.getCheck_uri())){
			return true;
		}
		return false;
	}
	
	public void doFilter(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		if(requireCheckLogin(request)){
			if(request.getSession().getAttribute(SECURITY_SESSION_USER) != null){
				response.sendRedirect(request.getContextPath()+ApplicationConfig.getIndex_uri());
				return ;
			}
			
			String username = (String) request.getParameter(SESSION_ATTR_USERNAME);
			String password = (String) request.getParameter(SESSION_ATTR_PASSWORD);
			log.debugf("username:%s,password:%s",username,password);
			if(username == null) 
				username = "";
			if(password == null)
				password = "";
			if(authHomeService == null)
				authHomeService = getAuthHomeServiceByIoc(request);
			UserHolder userHolder = authHomeService.loadUserByUserName(username);
			boolean result = true;
			if(result && userHolder == null){
				request.getSession().setAttribute("login_error", "用户名或密码错误");
				result = false;
			}
			password = Md5.encode(username+password);
			if(result && !password.equals(userHolder.getPassword())){
				request.getSession().setAttribute("login_error", "用户名或密码错误");
				result = false;
			}
			if(result && userHolder.getUserState() != User.STATE_SUCCESS){
				request.getSession().setAttribute("login_error", "该用户尚在审核中");
				result = false;
			}
			if(result){
				request.getSession().setAttribute(SECURITY_SESSION_USER, userHolder);
				String target = getTargetUrl(request);
				response.sendRedirect(target);
				return ;
			}else{
				response.sendRedirect(request.getContextPath()+ApplicationConfig.getLogin_uri()+"?error=error");
				return ;
			}
		}else{
			chain.doFilter(request, response);
		}
	}
	private AuthHomeService getAuthHomeServiceByIoc(HttpServletRequest request) throws ServletException{
		Ioc ioc = Mvcs.getIoc(request.getSession().getServletContext());
		authHomeService = ioc.get(null, "authHomeService");
		if(authHomeService == null) 
			throw new ServletException("没有找到认证模块");
		return authHomeService;
	}
	private String getTargetUrl(HttpServletRequest request){
		String target = (String) request.getSession().getAttribute(SESSION_TARGET_URL);
		if(Strings.isEmpty(target)){
			target = ApplicationConfig.getIndex_uri();
			if(Strings.isEmpty(target)){
				return "/";
			}
		}else{
			request.getSession().removeAttribute(SESSION_TARGET_URL);
		}
		return target;
	}
}
